package com.ruoyi.generator.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.entity.dto.CustomerExportVo;
import com.ruoyi.generator.mapper.CustomerMapper;
import com.ruoyi.generator.mapper.InvoiceFormMapper;
import com.ruoyi.generator.mapper.ContractMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.util.*;

/**
 * 业务字段 服务层实现
 * 
 * @author ruoyi
 */
@Service
public class CustomerServiceImpl implements CustomerService
{
	@Autowired
	private CustomerMapper CustomerMapper;
	@Autowired
	private InvoiceFormMapper InvoiceFormMapper;

	@Autowired
	private ContractMapper ContractMapper;

	@Autowired
	protected Validator validator;

    /**
     * 新增业务字段
     * 
     * @param Customer 业务字段信息
     * @return 结果
     */
	@Override
	public int insertCustomer(Customer Customer) {
//		/*验证合同编号是否存在*/
//		Contract contract = registrationMapper.selectContractByNumber(Contract.getContractNumber());
//		if(contract!= null){
//			return 0;
//		}
		/*生成合同编号*/


		try {
			// 生成客户编号
			String year = String.valueOf(Year.now().getValue());
			String Code = String.valueOf(CustomerMapper.getMaxCustomerNumber());
			String CustomerCode;

			// 生成编号逻辑
			if (Code == null || "null".equals(Code)) {
				CustomerCode = "ST" + year + "0001";
			} else {
				int num = Integer.parseInt(Code) + 1;
				CustomerCode = String.format("ST%s%04d", year, num);
			}

			// 设置客户编号
			Customer.setCustomerCode(CustomerCode);


			List<Contacts> contactsList = Customer.getContacts();
			for (Contacts contacts : contactsList) {
				Contacts contact = new Contacts();
				contact.setContactName(contacts.getContactName());
				contact.setBirthday(contacts.getBirthday());
				contact.setCustomerID(CustomerCode);
				contact.setPhone(contacts.getPhone());
				CustomerMapper.insertContacts(contact);
			}


			// 设置创建和更新信息
			Date now = new Date();
			String currentUsername = SecurityUtils.getUsername(); // 假设你使用Spring Security

			Customer.setCreateBy(currentUsername);
			Customer.setCreateTime(now);
			Customer.setUpdateBy(currentUsername);
			Customer.setUpdateTime(now);
			Customer.setDelFlag("0"); // 假设0表示未删除

			CustomerInvoice customerInvoice =new CustomerInvoice();
			customerInvoice.setCustomerName(Customer.getCustomerName());
			customerInvoice.setCustomerCode(Customer.getCustomerCode());
			//生成随机发票代码10位数 前来两位数是 ST 后八位是 表的长度
			Long id =CustomerMapper.selectInvoiceMaxId();
			String invoiceCode = "ST"+year+String.format("%06d",id);
			customerInvoice.setInvoiceCode(invoiceCode);
			customerInvoice.setInvoiceName(Customer.getCustomerName());
			customerInvoice.setTaxNumber(Customer.getTaxNumber());
			customerInvoice.setInvoiceAddress(Customer.getInvoiceAddress());
			customerInvoice.setInvoicePhone(Customer.getInvoicePhone());
			customerInvoice.setBankName(Customer.getBankName());
			customerInvoice.setBankAccount(Customer.getBankAccount());
			customerInvoice.setInvoiceType("普通发票");
			customerInvoice.setRemark(Customer.getInvoiceRemark());
			CustomerMapper.insertCustomerInvoice(customerInvoice);
			Customer.setInvoiceCode(invoiceCode);

			//拼接省市区
			Customer.setProvinceCityDistrict(Customer.getProvince() + Customer.getCity() + Customer.getDistrict());

			// 插入数据
			return CustomerMapper.insertCustomer(Customer);

		} catch (Exception e) {
			throw new RuntimeException("插入客户信息失败", e);
		}
	}


	@Override
	public List<Customer> selectCustomerList(CustomerSearchCriteria CustomerSearchCriteria) {
		return CustomerMapper.selectCustomerList(CustomerSearchCriteria);
	}

	@Override
	public int updateCustomerByCode(Customer Customer) {
		// 修改联系人

		List<Integer> contactIds = new ArrayList<>();
		for (Contacts contact : Customer.getContacts()) {
			if (contact.getId() != null){
				contactIds.add(Integer.valueOf(contact.getId()));

			}
		}
		Map<String, Object> params = new HashMap<>();

		// 确保 contactIds 非空
		if (!contactIds.isEmpty()) {
			params.put("ids", contactIds);
			params.put("customerId", Customer.getCustomerCode());
			CustomerMapper.UpdateContactsById(params);
		} else  {
			CustomerMapper.UpdateContactsByCustomerId(Customer.getCustomerCode());
			System.out.println("No valid contact IDs found to update.");
		}
		for (Contacts contact : Customer.getContacts()) {
			if (contact.getId() != null) {
				//先去数据库查询是否有该id的
				Contacts cont = CustomerMapper.selectContactsById(contact.getId());
				if (cont != null) {
					// 存在则更新
					contact.setCustomerID(cont.getCustomerID());
					contact.setId(cont.getId());
					CustomerMapper.UpdateContacts(contact);
				} else {
					// 不存在则插入
					contact.setCustomerID(Customer.getCustomerCode());
					CustomerMapper.insertContacts(contact);
				}
			}else {
				// 不存在则插入
				contact.setCustomerID(Customer.getCustomerCode());
				CustomerMapper.insertContacts(contact);
			}
		}



		//修改发票信息
		CustomerInvoice customerInvoice =new CustomerInvoice();
		customerInvoice.setCustomerCode(Customer.getCustomerCode());
		customerInvoice.setInvoiceName(Customer.getCustomerName());
		customerInvoice.setTaxNumber(Customer.getTaxNumber());
		customerInvoice.setInvoiceAddress(Customer.getInvoiceAddress());
		customerInvoice.setInvoicePhone(Customer.getInvoicePhone());
		customerInvoice.setBankName(Customer.getBankName());
		customerInvoice.setBankAccount(Customer.getBankAccount());
		customerInvoice.setUpdateTime(new Date());
		customerInvoice.setRemark(Customer.getInvoiceRemark());
		CustomerMapper.updateCustomerInvoice(customerInvoice);

		// 日期格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 处理生日
//		if (Customer.getBirthday() != null) {
//			try {
//				if (Customer.getBirthday() instanceof String) {
//					// 如果已经是字符串格式，验证格式是否正确
//					Date birthDate = sdf.parse(Customer.getBirthday().toString());
//					String birthday = sdf.format(birthDate);
//					Customer.setBirthday(birthday);
//				}
//			} catch (ParseException e) {
//				// 日期格式错误处理
//				throw new RuntimeException("生日日期格式错误", e);
//			}
//		}

		// 处理最后通讯时间
//		if (Customer.getLastCommunication() != null) {
//			try {
//				if (Customer.getLastCommunication() instanceof String) {
//					// 如果已经是字符串格式，验证格式是否正确
//					Date lastCommDate = sdf.parse(Customer.getLastCommunication().toString());
//					String lastComm = sdf.format(lastCommDate);
//					Customer.setLastCommunication(lastComm);
//				}
//			} catch (ParseException e) {
//				// 日期格式错误处理
//				throw new RuntimeException("最后通讯时间格式错误", e);
//			}
//		}


		// 设置更新时间和更新人
		Customer.setUpdateTime(new Date());
		//登录用户中获取
		Customer.setUpdateBy(SecurityUtils.getUsername());

		// 根据customerCode更新客户信息
		return CustomerMapper.updateCustomerByCode(Customer);

	}


	@Override
	public void deleteCustomerBycustomerCode(String customerCode) {
		// 根据customerCode删除客户信息
		Customer Customer = new Customer();
		Customer.setCustomerCode(customerCode);
		Customer customer = CustomerMapper.selectCustomerByCode(Customer);
		if (customer != null) {
			customer.setDelFlag("1"); // 1表示已删除
			// 设置更新时间和更新人
			customer.setUpdateTime(new Date());
			//登录用户中获取
			customer.setUpdateBy(SecurityUtils.getUsername());
			CustomerMapper.updateCustomerByCode(customer);
		}
	}


	@Override
	public int addVisit(CustomerVisit customerVisit) {

		Customer Customer = new Customer();
		Customer.setCustomerCode(customerVisit.getCustomerCode());
		Customer.setLastCommunication(new Date());
		CustomerMapper.updateCustomerByCode(Customer);
		customerVisit.setIsDeleted("0");
		customerVisit.setVisitTime(new Date());
		customerVisit.setLastCommunicationTime(new Date());
		customerVisit.setVisitLocation(customerVisit.getAddress());
		return  CustomerMapper.addVisit(customerVisit);
	}

	@Override
	public List<CustomerVisit> selectCustomerVisitList(CustomerVisitSearchCriteria customerVisitSearchCriteria) {
		return CustomerMapper.selectCustomerVisitList(customerVisitSearchCriteria);
	}

	@Override
	public int updateVisit(CustomerVisit customerVisit) {
		return  CustomerMapper.updateVisit(customerVisit);
	}

	@Override
	public Customer selectCustomerBycustomerCode(String customerCode) {
		System.out.println("查询的 customerCode: " + customerCode);
		Customer customerCode1 = new Customer();
		customerCode1.setCustomerCode(customerCode);
		Customer Customer = CustomerMapper.selectCustomerByCode(customerCode1);
		Customer.setContacts(CustomerMapper.selectContacts(customerCode));
		return Customer;
	}

	@Override
	public int addInvoice(InvoiceForm invoiceForm) {
		System.out.println("查询的 customerCode: " + invoiceForm);
		//通过合同号查询合同金额
		Contract contract = ContractMapper.selectContractByCode(invoiceForm.getContractNumber());
		if (contract == null) {
			return 2;// 合同不存在返回错误码
		}
		double contractAmount = contract.getEffectiveAmount();

		List<InvoiceForm> invoiceFormList = InvoiceFormMapper.selectInvoiceByContractNumber(invoiceForm.getContractNumber());
		double totalAmount = 0.0;
		for (InvoiceForm invoiceForm1 : invoiceFormList) {
			totalAmount += Double.parseDouble(String.valueOf(invoiceForm1.getInvoiceAmount()));
		}
		double currentAmount = Double.parseDouble(String.valueOf(invoiceForm.getInvoiceAmount()));
		if (totalAmount + currentAmount > contractAmount) {
			return 3; // 已开发票总额超过合同金额返回错误码
		}

		invoiceForm.setContractNumberAmount(invoiceForm.getContractNumber() + "服务周期（" + invoiceForm.getStartDate() + "至" + invoiceForm.getEndDate() + "）" + "发票金额：" + invoiceForm.getInvoiceAmount());
		invoiceForm.setAvailableAmount(String.valueOf(invoiceForm.getInvoiceAmount()));
		return InvoiceFormMapper.insertInvoiceForm(invoiceForm);
	}

	@Override
	public List<InvoiceForm> selectInvoiceByContractNumber(String contractCode) {
		System.out.println("查询的 contractCode: " + contractCode);
		return InvoiceFormMapper.selectInvoiceByContractNumber(contractCode);
	}

	@Override
	public CustomerInvoice queryCustomerInvoiceByCustomerCode(String clientName) {
		System.out.println("查询的 clientName: " + clientName);
		return CustomerMapper.queryCustomerInvoiceByCustomerCode(clientName);
	}

	@Override
	public CustomerInvoice queryCustomerInvoiceByClientName(String clientName) {
		System.out.println("查询的 clientName: " + clientName);
		return CustomerMapper.queryCustomerInvoiceByClientName(clientName);
	}

	@Override
	public List<Customer> queryMesBycustomerName(String customerName) {
		System.out.println("查询的 customerName: " + customerName);
		return CustomerMapper.queryMesBycustomerName(customerName);
	}

	@Override
	public String queryStartDateByContractNumber(String contractCode) {
		System.out.println("查询的 contractCode: " + contractCode);
		String startDate = CustomerMapper.queryStartDateByContractNumber(contractCode);

		//判断是null
		if (startDate == null) {
			return null;
		}

		// 将 startDate 转换为 LocalDate
		LocalDate localDate = LocalDate.parse(startDate);

		// 加一天
		LocalDate nextDay = localDate.plusDays(1);

		// 判断是否为月末最后一天
		if (nextDay.getMonthValue() != localDate.getMonthValue()) {
			// 如果加一天后月份发生变化，说明是月末最后一天，返回下个月一号
			nextDay = nextDay.withDayOfMonth(1);
		}

		// 返回格式化后的日期字符串
		return nextDay.toString();
	}

	@Override
	public String addCustomerList(List<CustomerInfo> userList) {
		List<String> errorMessages = new ArrayList<>();
		int successCount = 0;
		int totalCount = userList.size();
		
		for (int i = 0; i < userList.size(); i++) {
			CustomerInfo customerInfo = userList.get(i);
			List<String> rowErrors = new ArrayList<>();
			int rowNumber = i + 1; // 行号从1开始
			
			// 验证必填字段
			if (StringUtils.isEmpty(customerInfo.getCustomerName())) {
				rowErrors.add("客户名称不能为空");
			}

			Customer checkCustomer = new Customer();
			checkCustomer.setCustomerName(customerInfo.getCustomerName());
			checkCustomer.setDelFlag("0");
			Customer customer1 = CustomerMapper.selectCustomerByCode(checkCustomer);
			if (customer1 != null) {
				rowErrors.add("客户名称已存在");
			}
			
			if (StringUtils.isEmpty(customerInfo.getProvince())) {
				rowErrors.add("省份不能为空");
			}
			
			if (StringUtils.isEmpty(customerInfo.getCity())) {
				rowErrors.add("市不能为空");
			}
			
			if (StringUtils.isEmpty(customerInfo.getDistrict())) {
				rowErrors.add("区不能为空");
			}
			
			if (StringUtils.isEmpty(customerInfo.getAccountManager())) {
				rowErrors.add("客户经理不能为空");
			}

//			if (StringUtils.isEmpty(customerInfo.getContactPerson())) {
//				rowErrors.add("联系人不能为空");
//			}
			
			// 验证手机号格式
			if (StringUtils.isNotEmpty(customerInfo.getPhoneNumber())) {
				String phonePattern = "^1[3-9]\\d{9}$";
				if (!customerInfo.getPhoneNumber().matches(phonePattern)) {
					rowErrors.add("手机号格式不正确");
				}
			}
//			if (StringUtils.isNotEmpty(customerInfo.getKaiPiaoContactPhone())) {
//				String phonePattern = "^1[3-9]\\d{9}$";
//				if (!customerInfo.getKaiPiaoContactPhone().matches(phonePattern)) {
//					rowErrors.add("开票联系手机号格式不正确");
//				}
//			}
			
			// 验证税号格式（如果提供）
			if (StringUtils.isNotEmpty(customerInfo.getTaxNumber())) {
				if (customerInfo.getTaxNumber().length() < 15 || customerInfo.getTaxNumber().length() > 20) {
					rowErrors.add("税号长度应在15-20位之间");
				}
			}
			
			// 验证银行账号格式（如果提供）
			if (StringUtils.isNotEmpty(customerInfo.getBankAccount())) {
				if (customerInfo.getBankAccount().length() < 10 || customerInfo.getBankAccount().length() > 25) {
					rowErrors.add("银行账号长度应在10-25位之间");
				}
			}
			
			// 如果当前行有错误，记录错误信息
			if (!rowErrors.isEmpty()) {
				errorMessages.add("第" + rowNumber + "行数据错误：" + String.join("，", rowErrors));
				continue; // 跳过当前行，继续处理下一行
			}
			
			// 数据验证通过，创建客户对象
			try {
				Customer customer = new Customer();
				customer.setCustomerName(customerInfo.getCustomerName());//客户名称
				customer.setProvince(customerInfo.getProvince());//省
				customer.setCity(customerInfo.getCity());//市
				customer.setDistrict(customerInfo.getDistrict());//区
				customer.setManager(customerInfo.getAccountManager());//客户经理
				customer.setAddress(customerInfo.getDetailedAddress());//详细地址
				customer.setRemark(customerInfo.getRemark());
				customer.setInvoiceRemark(customerInfo.getInvoiceRemark());
				
				//客户联系人信息
				List<Contacts> contacts = new ArrayList<>();
				Contacts contact = new Contacts();
				if (customerInfo.getContactPerson() != null) {
					contact.setContactName(customerInfo.getContactPerson());
				}
				if (customerInfo.getPhoneNumber() != null) {
					contact.setPhone(customerInfo.getPhoneNumber());
				}
				// 日期格式化处理
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
				if(customerInfo.getBirthday() != null){
					contact.setBirthday(sdf.format(customerInfo.getBirthday()));
				}
				contacts.add(contact);

				customer.setCompanyType(customerInfo.getCompanyType());//公司类型
				customer.setCompanySize(customerInfo.getCompanyScale());//公司规模
				customer.setIndustry(customerInfo.getIndustry());//所属行业
				customer.setStarLevel(customerInfo.getCustomerStarLevel());//客户星级
				customer.setInvoiceName(customerInfo.getUnitName());//单位名称
				customer.setInvoiceAddress(customerInfo.getUnitAddress());//单位地址
				customer.setTaxNumber(customerInfo.getTaxNumber());//税号
				customer.setInvoicePhone(customerInfo.getKaiPiaoContactPhone());//开票联系电话
				customer.setBankName(customerInfo.getBankName());
				customer.setBankAccount(customerInfo.getBankAccount());
				customer.setContacts(contacts);
				customer.setStatus("pending");
				
				//插入客户信息
				insertCustomer(customer);
				successCount++;
				
			} catch (Exception e) {
				errorMessages.add("第" + rowNumber + "行数据处理失败：" + e.getMessage());
			}
		}
		
		// 返回处理结果
		if (errorMessages.isEmpty()) {
			return "上传成功！共处理" + totalCount + "条数据，全部导入成功。";
		} else {
			StringBuilder result = new StringBuilder();
			result.append("数据处理完成！共处理").append(totalCount).append("条数据，")
				  .append("成功导入").append(successCount).append("条，")
				  .append("失败").append(errorMessages.size()).append("条。\n\n");
			result.append("错误详情：\n");
			for (String error : errorMessages) {
				result.append(error).append("\n");
			}
			return result.toString();
		}
	}

	@Override
	public List<ExportCustomer> exportCustomerList(CustomerExportSearchCriteria customerSearchCriteria) {
		List<ExportCustomer> CustomerList=CustomerMapper.exportCustomerList(customerSearchCriteria);
		return CustomerList;
	}

	

	@Override
	public List<CustomerExportVo> pushCustomerList(CustomerExportSearchCriteria customerExportSearchCriteria) {
        List<CustomerExportVo> CustomerList = CustomerMapper.selectCustomerVoList(customerExportSearchCriteria);
        return CustomerList;
	}


}
